import os
from datetime import datetime, timedelta

from pathlib import Path

import pymysql
from django.contrib.sessions.backends import file

import logs

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-lfxh)v@xec^mp))tngqj(71!eny8zs+f30_!o^9sd$tn@^o@rv'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'production_line.apps.ProductionLineConfig',
    'rest_framework',
    'rest_framework_simplejwt',
    'corsheaders',
    'logs'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'corsheaders.middleware.CorsMiddleware',  # 跨域
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'common.Middleware.JwtMiddleware.JwtMiddleware',
]

ROOT_URLCONF = 'backend.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': []
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'backend.wsgi.application'

# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases

DATABASES = {
    # 'default': {
    #     'ENGINE': 'django.db.backends.sqlite3',
    #     'NAME': BASE_DIR / 'db.sqlite3',
    # }
    'default': {
        # 说明你要连的库为mysql
        'ENGINE': 'django.db.backends.mysql',
        # 数据库名称
        'NAME': 'product_vue',
        # IP 本地为127.0.0.1
        'HOST': '127.0.0.1',
        # 端口默认是3306 oracel默认端口1521
        'PORT': '3306',
        # 数据库用户
        'USER': 'root',
        # 数据库密码
        'PASSWORD': '457896',
    }
}
pymysql.version_info = (1, 4, 6, "final", 0)
pymysql.install_as_MySQLdb()
# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# drf配置
REST_FRAMEWORK = {
    # 全局配置异常处理程序
    'EXCEPTION_HANDLER': 'common.utils.exception.custom_exception_handler',

    # 修改默认返回JSON的渲染器的类
    'DEFAULT_RENDERER_CLASSES': (
        'common.utils.rendererresponse.CustomRenderer',
    ),

}

# JWT 配置
SKY_JWT = {
    'ADMIN_SECRET_KEY': SECRET_KEY,  # 直接用 SECRET_KEY
    'ADMIN_TTL': 60 * 60 * 2,  # 令牌过期时间（秒）
    'ADMIN_TOKEN_NAME': 'admin_token',

    'USER_SECRET_KEY': 'your_user_secret_key',
    'USER_TTL': 7200,  # 令牌过期时间（秒）
    'USER_TOKEN_NAME': 'user_token',
}
# 跨域增加忽略
# 在 setting.py 末尾添加以下设置
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_HEADERS = ('*')
CORS_ALLOW_METHODS = (
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
    'VIEW',
)




# 日志

# 日志配置
# LOGGING = {
#     'version': 1,
#     'disable_existing_loggers': False,
#     'formatters': {
#         'verbose': {
#             'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}',
#             'style': '{',
#         },
#         'simple': {
#             'format': '{levelname} {message}',
#             'style': '{',
#         },
#         "default": {
#             "format": '%(asctime)s %(name)s  %(pathname)s:%(lineno)d %(module)s:%(funcName)s '
#                       '%(levelname)s- %(message)s',
#             "datefmt": "%Y-%m-%d %H:%M:%S"
#         },
#     },
#     'handlers': {
#         'console': {
#             'level': 'DEBUG',
#             'class': 'logging.StreamHandler',
#             'formatter': 'default'
#         },
#         'file': {
#             'level': 'DEBUG',
#             'class': 'logging.handlers.TimedRotatingFileHandler',
#             'filename': os.path.join(BASE_DIR, 'logs/debug.log'),
#             'when': "D",
#             'interval': 1,
#             'formatter': 'default'
#         },
#         "request": {
#             'level': 'DEBUG',
#             'class': 'logging.FileHandler',
#             'filename': os.path.join(BASE_DIR, 'logs/request.log'),
#             'formatter': 'default'
#         },
#         "server": {
#             'level': 'DEBUG',
#             'class': 'logging.FileHandler',
#             'filename': os.path.join(BASE_DIR, 'logs/server.log'),
#             'formatter': 'default'
#         },
#         "root": {
#             'level': 'DEBUG',
#             'class': 'logging.FileHandler',
#             'filename': os.path.join(BASE_DIR, 'logs/root.log'),
#             'formatter': 'default'
#         },
#
#         "db_backends": {
#             'level': 'DEBUG',
#             'class': 'logging.FileHandler',
#             'filename': os.path.join(BASE_DIR, 'logs/db_backends.log'),
#             'formatter': 'default'
#         },
#         "autoreload": {
#             'level': 'INFO',
#             'class': 'logging.FileHandler',
#             'filename': os.path.join(BASE_DIR, 'logs/autoreload.log'),
#             'formatter': 'default'
#         }
#     },
#     'loggers': {
#         # 应用中自定义日志记录器
#         'mylogger': {
#             'level': 'DEBUG',
#             'handlers': ['console', 'file'],
#             'propagate': True,
#         },
#         "django": {
#             "level": "DEBUG",
#             "handlers": ["console", "file"],
#             'propagate': False,
#         },
#         "django.request": {
#             "level": "DEBUG",
#             "handlers": ["request"],
#             'propagate': False,
#         },
#         "django.server": {
#             "level": "DEBUG",
#             "handlers": ["server"],
#             'propagate': False,
#         },
#         "django.db.backends": {
#             "level": "DEBUG",
#             "handlers": ["db_backends"],
#             'propagate': False,
#         },
#         "django.utils.autoreload": {
#             "level": "INFO",
#             "handlers": ["autoreload"],
#             'propagate': False,
#         }
#     },
#     'root': {
#         "level": "DEBUG",
#         "handlers": ["root"],
#     }
# }



LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
        },
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': os.path.join(BASE_DIR, 'logs', 'file.log'),
        },
    },
    'loggers': {
        '': {
            'handlers': ['console', 'file'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

